package com.airtight.util;

import android.content.Context;
import android.content.res.Resources;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class TextResourceReader {

    /**turns a file into a string of text*/
    public static String readTextFileFromResource(Context context, int resourceId){
        StringBuilder body = new StringBuilder();

        try {
            InputStream inputStream = context.getResources().openRawResource(resourceId);           //creates an input stream of the resource
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);               //creates an input stream reader
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);                  //creates a buffered reader

            String nextLine;

            while ((nextLine = bufferedReader.readLine()) != null) {                                //reads the entire resource
                body.append(nextLine);
                body.append('\n');
            }
        }
        catch (IOException e){
            throw new RuntimeException("Could not open resource: "+resourceId, e);
        }
        catch (Resources.NotFoundException nfe){
            throw new RuntimeException("Resources not found: "+ resourceId, nfe);
        }

        return body.toString();                                                                     //returns recourse as String
    }
}
